package com.yuexunit.mobilenurse.module.Chemical.ui;

import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;

import com.imscs.barcodemanager.BarcodeManager;
import com.imscs.barcodemanager.Constants;
import com.yuexunit.mobilenurse.R;
import com.yuexunit.mobilenurse.config.AppConfig;

import org.kymjs.kjframe.KJActivity;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.io.IOException;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by work-jx on 2016/8/18.
 */
public class Act_ChemicalSearch_M80 extends KJActivity implements BarcodeManager.OnEngineStatus{
    @Bind(R.id.chemicalsearch_edt)
    EditText chemicalsearchEdt;

    //扫描
    private DoDecodeThread mDoDecodeThread;
    private BarcodeManager mBarcodeManager = null;
    private final int SCANKEY_LEFT = 301;
    private final int SCANKEY_RIGHT = 300;
    private final int SCANKEY_CENTER = 302;
    private final int SCANTIMEOUT = 3000;
    private Handler mDoDecodeHandler;
    private boolean mbKeyDown = true;
    class DoDecodeThread extends Thread {
        public void run() {
            Looper.prepare();
            mDoDecodeHandler = new Handler();
            Looper.loop();
        }
    }

    @Override
    public void setRootView() {
        setContentView(R.layout.act_chemiaclsearch);
        ButterKnife.bind(this);

        mDoDecodeThread = new DoDecodeThread();
        mDoDecodeThread.start();
    }

    @Override
    public void onResume(){
        super.onResume();
        if (mBarcodeManager == null) {
            // initialize decodemanager
            mBarcodeManager = new BarcodeManager(this, this);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(mBarcodeManager != null) {
            try {
                mBarcodeManager.release();
                mBarcodeManager = null;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onStop(){
        super.onStop();

    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        if (mBarcodeManager != null) {
            try {

                mBarcodeManager.release();
                mBarcodeManager = null;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    @OnClick({R.id.chemicalsearch_img_back, R.id.chemicalsearch_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.chemicalsearch_img_back:
                finish();
                break;
            case R.id.chemicalsearch_btn:
                if(chemicalsearchEdt.getText().toString().length() == Integer.valueOf(PreferenceHelper.readString(aty, AppConfig.JCI_INFO, AppConfig.JCI_PTSM_RULE))) {
                    String type_tag = chemicalsearchEdt.getText().toString().substring(8, 9);
                    if (type_tag.equals(AppConfig.TAG_INJECTION)) {
                        Intent intent_new = new Intent();
                        intent_new.setClass(aty, Act_ChemicalDetail.class);
                        intent_new.putExtra("barcode", chemicalsearchEdt.getText().toString());
//                    intent_new.putExtra("barcode", "20160628100176");
                        startActivity(intent_new);
                        chemicalsearchEdt.setText("");
                    } else {
                        ViewInject.toast("非化药条码");
                    }
                }
                else{
                    ViewInject.toast("非化药条码");
                }
                break;
        }
    }

    private void doScanInBackground() {
        mDoDecodeHandler.post(new Runnable() {

            @Override
            public void run() {
                if (mBarcodeManager != null) {
                    // TODO Auto-generated method stub
                    try {
                        synchronized (mBarcodeManager) {
                            mBarcodeManager.executeScan(SCANTIMEOUT);
                        }

                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        switch (keyCode) {
            case KeyEvent.KEYCODE_ENTER:
            case SCANKEY_LEFT:
            case SCANKEY_CENTER:
            case SCANKEY_RIGHT:
            case KeyEvent.KEYCODE_SLASH: // hal key
                try {
                    if (mbKeyDown) {
                        DoScan();
                        mbKeyDown = false;
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return true;
            case KeyEvent.KEYCODE_BACK:
                this.finish();
                return true;
            default:
                return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_ENTER:
            case SCANKEY_LEFT:
            case SCANKEY_CENTER:
            case SCANKEY_RIGHT:
            case KeyEvent.KEYCODE_SLASH: // hal key
                try {
                    mbKeyDown = true;
                    cancleScan();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return true;
            case KeyEvent.KEYCODE_BACK:
                this.finish();
                return true;
            default:
                return super.onKeyUp(keyCode, event);
        }
    }

    private void DoScan() throws Exception {
        doScanInBackground();
    }

    private void cancleScan() throws Exception {
        if (mBarcodeManager != null) {
            mBarcodeManager.exitScan();
        }
    }

    @Override
    public void onEngineReady() {
        // TODO Auto-generated method stub
        ScanResultHandler.sendEmptyMessage(Constants.DecoderReturnCode.RESULT_DECODER_READY);
    }

    @Override
    public int scanResult(boolean suc,BarcodeManager.ScanResult result) {
        // TODO Auto-generated method stub
        Message m = new Message();
        m.obj = result;
        if (suc){
            // docode successfully
            m.what = Constants.DecoderReturnCode.RESULT_SCAN_SUCCESS;
        }else{
            m.what = Constants.DecoderReturnCode.RESULT_SCAN_FAIL;

        }
        ScanResultHandler.sendMessage(m);
        return 0;
    }

    private Handler ScanResultHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Constants.DecoderReturnCode.RESULT_SCAN_SUCCESS:
                    String strDecodeResult = "";
                    BarcodeManager.ScanResult decodeResult = (BarcodeManager.ScanResult) msg.obj;

                    String result = decodeResult.result;
                    if (mBarcodeManager != null) {
                        mBarcodeManager.beepScanSuccess();
                    }

                    if (result.length() == Integer.valueOf(PreferenceHelper.readString(aty, AppConfig.JCI_INFO, AppConfig.JCI_PTSM_RULE)))
                    {
                        String type_tag = result.substring(8, 9);
                        if(type_tag.equals(AppConfig.TAG_INJECTION)) {
                            Intent intent_new = new Intent();
                            intent_new.setClass(aty, Act_ChemicalDetail.class);
                            intent_new.putExtra("barcode", result);
                            startActivity(intent_new);
                            chemicalsearchEdt.setText("");
                        }
                        else {
                            ViewInject.toast("非化药条码");
                        }
                    }
                    else{
                        ViewInject.toast("非化药条码");
                    }
                    break;

                case Constants.DecoderReturnCode.RESULT_SCAN_FAIL: {
                    if (mBarcodeManager != null) {
                        mBarcodeManager.beepScanFail();
                    }
                }
                break;
                case Constants.DecoderReturnCode.RESULT_DECODER_READY: {
                }
                break;
                default:
                    super.handleMessage(msg);
                    break;
            }
        }
    };
}
